經過實作後,情境如下
儲存按鈕<button type="submit" id="btn-save-form" form="myform" title="Save" class="btn btn-primary"></button>
//創建一個自訂函數
function myBeforeUnload(event){
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
}
//頁面載入後,使用監聽事件的方式去呼叫該函數
window.addEventListener('beforeunload', myBeforeUnload);
//點擊儲存按鈕之後,取消監聽事件
$('#btn-save-form').on('click', function(){
window.removeEventListener('beforeunload', myBeforeUnload);
});
//若在 input 元素觸發 focusin (滑鼠點入),則新增監聽事件
$("input").focusin(function() {
window.addEventListener('beforeunload', myBeforeUnload);
});
歡迎補充 ios 的做法以及優化…
window.removeEventListener with a named function isn't working
https://stackoverflow.com/questions/38223945/window-removeeventlistener-with-a-named-function-isnt-working
坑啊 ios已经废弃beforeunload事件
https://blog.csdn.net/fighting_sunnyGirl/article/details/103407617